package com.aboo.action;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.aboo.po.AdminUserPO;
import com.aboo.po.MenuPO;
import com.aboo.pub.constant.RequestConstants;
import com.aboo.pub.constant.SessionConstant;
import com.aboo.pub.exception.BasicException;
import com.aboo.pub.result.ResultConstant;
import com.aboo.pub.token.AdminLoginToken;
import com.aboo.service.AdminUserService;
import com.aboo.util.DateUtil;
import com.aboo.util.RequestUtil;
import com.aboo.util.SessionUtil;

public class AdminFrameAction extends BaseAction {

	private static final long serialVersionUID = -2053992228168833028L;
	private AdminUserService adminUserService;
	
	public String login() throws BasicException {
		return BaseAction.LOGIN;
	}
	
	public String index() throws BasicException {
		return BaseAction.INDEX;
	}
	
	public String loginExc() throws BasicException {
		String userName = RequestUtil.getParameterString(request, "userName");
		String userPwd = RequestUtil.getParameterString(request, "userPwd");
		String securityCode = RequestUtil.getParameterString(request, "securityCode");
		
		if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(userPwd) || StringUtils.isEmpty(securityCode)) {
			return BaseAction.LOGIN;
		}
		
		if (!securityCode.equals(SessionUtil.getString(request, RequestConstants.ADMIN_SECURITY_CODE))) {
			SessionUtil.removeAttribute(request, RequestConstants.ADMIN_SECURITY_CODE);
			ri.setResultCode(ResultConstant.STATUS_ERROR);
			throw new BasicException("验证码输入错误！");
		}
		
		adminUserService.login(ri, request, userName, userPwd);
		
		AdminUserPO user = (AdminUserPO) ri.getObj();
		if (user == null) {
			throw new BasicException("用户名或密码输入错误！");
		}
		if (user.getId().intValue() != 1 && user.getExpiredDate().compareTo(DateUtil.getChar8()) < 0) {
			throw new BasicException("用户已过期，请联系管理员！");
		}
		
		if (ResultConstant.STATUS_OK.equals(ri.getResultCode())) {
			adminUserService.findUserMenuList(ri, user.getId());
			
			AdminLoginToken adminLoginToken = new AdminLoginToken();
			adminLoginToken.setAdminUserInfo(user);
			adminLoginToken.classify((List<MenuPO>) ri.getObj());
			SessionUtil.setAttribute(request, SessionConstant.ADMIN_LOGIN_TOKEN, adminLoginToken);
			return "loginExc";
		}
		
		return "loginExc";
	}
	
	public String loginOut() throws BasicException {
		//正式上线后，需替换
		//SessionUtil.invalidate(request);
		SessionUtil.removeAttribute(request, SessionConstant.ADMIN_LOGIN_TOKEN);
		return "loginOut";
	}

	public AdminUserService getAdminUserService() {
		return adminUserService;
	}
	public void setAdminUserService(AdminUserService adminUserService) {
		this.adminUserService = adminUserService;
	}

}
